package leetcode;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;

public class Solution3 {
    //二叉树的前序遍历
    public List<Integer> preorderTraversal(TreeNode root) {
        //二叉树的前序遍历  中左右
        ArrayList<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        //入栈顺序  中 右 左
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            result.add(node.val);
            if(node.right != null){
                stack.push(node.right);
            }
            if(node.left != null){
                stack.push(node.left);
            }
        }
        return result;
    }

}
